// pages/dashboard/dashboard.js
const analysis = require('../../utils/dataAnalysi.js')
const util = require('../../utils/util.js')
var appInstance = getApp()
var width = 0;
var height = 0;
var lineCtx = null;
var grid_width = 5;
var timeId = null;
Page({
    data:{
        temp_connected: false,
        bp_connected: false,
        spo2_connected: false,
        temp_value: "30.25",
        bp_value: "128/89",
        spo2_value: "--",
        pleth_value: "--",
        spo2_battery: 20,
        ecg_vital: {
            ecg_connected: false,
            ecg_battery: "-1",
            rr_value: "14",
        },
        connected_successful: false,
        incomplete: [],
    },
    onLoad(){
        console.log('dashboard onLoad')
        let that = this
        appInstance.watch(that.watchBack)
        // 回到主页面看ecg设备状态是否更新
        if (appInstance.globalData.ecg != null) {
            console.log(appInstance.globalData.ecg)
            let connect_status = appInstance.globalData.ecg.connected
            let battery = appInstance.globalData.ecg.battery
            let deviceName = appInstance.globalData.ecg.deviceName
            console.log(connect_status,battery)
            this.setData({
                ecg_vital:{
                    ecg_connected: connect_status,
                    ecg_battery: battery,
                    rr_value: "--",
                },
            })
            if (connect_status && !this.connected_successful) {
              this.queue = [];
              this.loop()
              this.connected_successful = true
              appInstance.writeBLECharacteristicValue(util.openRealTime())
              setTimeout(function() {
                  appInstance.writeBLECharacteristicValue(util.sendReplyAckCommand())
              }, 1000)
              //返回主页面连接成功后 
              wx.onBLECharacteristicValueChange((characteristic) => {
                // console.log('收到特征uuid:',characteristic.characteristicId)
                // console.log('收到的ori数据:',characteristic.value)
                console.log('收到的数据:',util.arrayToHexString(characteristic.value))
                var byteArray = new Uint8Array(characteristic.value)
                var valueStr = util.arrayToHexString(characteristic.value)
                var data_type = ''
                if (characteristic.characteristicId == '00002A29-0000-1000-8000-00805F9B34FB') {
                    //设备信息
                    data_type = '设备信息'
                    valueStr = util.utf8ByteToUnicodeStr(byteArray)
                }else if (characteristic.characteristicId == '00002A27-0000-1000-8000-00805F9B34FB') {
                    data_type = '硬件版本号'
                    valueStr = util.utf8ByteToUnicodeStr(byteArray)
                    let keyStr = deviceName.replace('ECGRec_', '') + valueStr
                    console.log("硬件版本号:",keyStr)
                    this.decryptKey = keyStr
                }else if (characteristic.characteristicId == '00002A26-0000-1000-8000-00805F9B34FB') {
                    data_type = '固件版本号'
                    valueStr = util.utf8ByteToUnicodeStr(byteArray)
                }else if (characteristic.characteristicId == '2344C102-7994-1CCA-B98B-00FFD0B3CA8A') {
                  if (byteArray[0] == 0x49 && byteArray.length > 20) {
                    let decryptBuffer = analysis.decryptEcgData(byteArray, appInstance.globalData.decryptKey)
                    if (byteArray[1] == 0) {
                        //有效数据长度
                        let effectiveLength = (decryptBuffer[2] << 8) + decryptBuffer[3]
                        console.log("有效长度:",effectiveLength)
                        //ecg长度
                        let ecgLength = (decryptBuffer[4] << 8) + decryptBuffer[5]
                        this.ecgEffLen = ecgLength
                        console.log("ecg模块长度:",ecgLength)
                        let effectiveData = new Uint8Array(decryptBuffer.slice(6))
                        console.log(effectiveData)
                        if (byteArray.length >= effectiveLength + 4 ) {
                            console.log("够了")
                            this.parseEcgPacket(effectiveData)
                        }else{
                            console.log("返回")
                            this.incomplete = effectiveData
                        }
                    }else if (byteArray[1] == 1) {
                        console.log("第二帧")
                        var incompleteBuffer = []
                        for (let i = 0; i < this.incomplete.length; i++) {
                          const element = this.incomplete[i];
                          incompleteBuffer.push(element)
                        }
                        // console.log("incompleteBuffer:",incompleteBuffer)
                        let eff = decryptBuffer.slice(2)
                        // console.log("eff:",eff)
                        for (let index = 0; index < eff.length; index++) {
                          let element = eff[index];
                          incompleteBuffer.push(element)
                        }
                        // console.log(incompleteBuffer)
                        
                        this.parseEcgPacket(incompleteBuffer)

                        // var rdlen = 0
                        // rdlen += 1

                        // let time = ((incompleteBuffer[1] << 24) & 0xFF000000) | ((incompleteBuffer[2] << 16) & 0xFF0000) | ((incompleteBuffer[3] << 8) & 0xFF00) | ((incompleteBuffer[4]) & 0xFF);
                        // console.log("time:",time)
                        // rdlen += 6
                        // //导联状态
                        // rdlen += 1
                        // rdlen += 10
                        // rdlen += 2
                        // rdlen += 5
                        // console.log("rdlen:",rdlen)
                        // let accLength = incompleteBuffer[rdlen]
                        // rdlen += 1
                        // console.log("acc长度",accLength)
                        // let ecgIndex = accLength + rdlen
                        // console.log("ecg位置",ecgIndex)
                        // let ecgTruthLen = this.ecgEffLen - ecgIndex
                        // console.log("ecg真实长度",ecgTruthLen)
                        // let ecgTruthBuffer = incompleteBuffer.slice(ecgIndex, ecgIndex+ecgTruthLen)
                        // console.log(ecgTruthBuffer)
                        // let decompressionData = analysis.decompression_data(ecgTruthBuffer)
                        // console.log("compression_data:",decompressionData)

                    }
                  }else{
                    let dataDict = analysis.analysisData(byteArray)
                    // this.incomplete = null
                    data_type = dataDict.type
                    if (data_type == "Battery") {
                      valueStr = dataDict.value

                        // appInstance.globalData.ecg.battery = valueStr
                        // appInstance.globalData.ecg = {battery:valueStr,connected:true}
                        let ecgDict = {ecg_battery:valueStr,ecg_connected:true}
                        this.setData({
                          ecg_vital:ecgDict,
                        })
                    }
                  }
                }
                // wx.showToast({
                //   title: '收到数据',
                // })
            })
            }
        }else{
          appInstance.globalData.ecg = {
              connected:false,
              battery: "100",
              deviceName: "",
            }
        }
    },
    watchBack(ecg){
        console.log('监听到数值变化=',ecg)
        this.setData({
            ecg_vital:{
                ecg_connected: ecg.connected,
                ecg_battery: ecg.battery,
            },
        })
    },
    //解析数据包
    parseEcgPacket(dataPacket){
        var rdlen = 0
        rdlen += 1
        let time = ((dataPacket[1] << 24) & 0xFF000000) | ((dataPacket[2] << 16) & 0xFF0000) | ((dataPacket[3] << 8) & 0xFF00) | ((dataPacket[4]) & 0xFF);
        console.log("time:",time)
        rdlen += 6
        //导联状态
        rdlen += 1
        rdlen += 10
        rdlen += 2
        rdlen += 5
        console.log("rdlen:",rdlen)
        let accLength = dataPacket[rdlen]
        rdlen += 1
        console.log("acc长度",accLength)
        let ecgIndex = accLength + rdlen
        console.log("ecg位置",ecgIndex)
        let ecgTruthLen = this.ecgEffLen - ecgIndex
        console.log("ecg真实长度",ecgTruthLen)
        let ecgTruthBuffer = dataPacket.slice(ecgIndex, ecgIndex+ecgTruthLen)
        // console.log(ecgTruthBuffer)
        let decompressionData = analysis.decompression_data(ecgTruthBuffer)
        this.addData(decompressionData)
        appInstance.writeBLECharacteristicValue(util.sendNextAckCommand())
    },
    onUnload(){
        console.log('dashboard onUnload')
    },
    pairSpo2(){
        wx.navigateTo({
          url: '../dashboard/pair/pair'+"?type=spo2",
        })
    },
    pairECG(){
        wx.navigateTo({
          url: '../dashboard/pair/pair'+"?type=ecg",
        })
    },
    pairTemp(){
        wx.navigateTo({
          url: '../dashboard/pair/pair'+"?type=temp",
        })
    },
    pairBP(){
        wx.navigateTo({
          url: '../dashboard/pair/pair'+"?type=bp",
        })
    },
    ecgSensorStatus(){
      console.log("ecgSensorStatus")
      let connectStatus = appInstance.globalData.ecg.connected
      if (connectStatus) {
        let hwStr = appInstance.globalData.hw
        let fwStr = appInstance.globalData.fw
        let sn = appInstance.globalData.ecg.deviceName.replace("ECGRec_","")
        let battery = appInstance.globalData.ecg.battery
        let param = "hw="+hwStr+"&"+"fw="+fwStr+"&"+"sn="+sn+"&"+"battery="+battery
        wx.navigateTo({
          url: '../dashboard/sensorStatus/sensorStatus'+"?"+param,
        })
      }else{
        wx.navigateTo({
          url: '../dashboard/pair/pair'+"?type=ecg",
        })
      }
    },
    onShow: function () {
        console.log("dashboard onShow")
        if (this.data.ecg_vital.ecg_connected) {
          //绘制网格
          this.defaultDraw()
          //准备绘图设置
          this.prepareDraw()
        }
        
    },
    //绘制背景
    defaultDraw:function (params) {
      wx.createSelectorQuery()
          .select('#bgCell')
          .fields({
            node: true,
            size: true,
          })
          .exec(this.default.bind(this))
    },
    default(res){
      let width = res[0].width
      let height = res[0].height
      const canvas = res[0].node
      var bglineCtx = canvas.getContext('2d')
      console.log("画布宽度:",width)
      console.log("画布高度:",height)
      var offsetx = 0;
      var offsety = 0;
      bglineCtx.fillStyle = "rgba(255,255,255,1)";
      bglineCtx.fillRect (offsetx, offsety, width, height);

      var d = 5;
      /*绘制竖行网格*/
      for (var i = 0; i <= width/d; i++)
      {
          if(i%5 == 0){
            bglineCtx.strokeStyle = "rgba(173, 170, 170,.6)";
            bglineCtx.lineWidth = 1;
          }else{
            bglineCtx.strokeStyle = "rgba(173, 170, 170,.3)";
            bglineCtx.lineWidth = 1;
          }
          bglineCtx.beginPath();
          bglineCtx.moveTo(i*d+offsetx,offsety);
          bglineCtx.lineTo(i*d+offsetx,height+offsety);
          bglineCtx.stroke();
      }

      /*绘制横行网格*/
      let col = 3.12
      for (var j = 0; j <= height/col; j++)
      {
          if (j%5 == 0){
            bglineCtx.strokeStyle = "rgba(173, 170, 170,.6)";
            bglineCtx.lineWidth = 0.6;
          }else{
            bglineCtx.strokeStyle = "rgba(173, 170, 170,.3)";
            bglineCtx.lineWidth = 0.6;
          }
          bglineCtx.beginPath();
          bglineCtx.moveTo(offsetx,j*col+offsety);
          bglineCtx.lineTo(width+offsetx,j*col+offsety);
          bglineCtx.stroke();
      }

      /*横纵坐标说明*/
      // lineCtx.fillStyle = "rgb(0,0,0)";
      // lineCtx.fillText("time/ms",offsetx+width/2,220);
      // lineCtx.fillText("0",offsetx,220);
      // lineCtx.fillText("10000",offsetx+width*49/50,220);

      // lineCtx.fillText("1.0mv",0,11);
      // lineCtx.fillText("0",20,102);
      // lineCtx.fillText("-1.0mv",0,200);
  
    },
    //预备绘制
    prepareDraw(){
      wx.createSelectorQuery()
          .select('#line')
          .fields({
            node: true,
            size: true,
          })
          .exec(this.init.bind(this))
    },
    
    init(res) {
        width = res[0].width
        height = res[0].height
        const canvas = res[0].node
        lineCtx = canvas.getContext('2d')
    
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = width * dpr
        canvas.height = height * dpr
        lineCtx.scale(dpr, dpr)

        this.currentX = 0;
        this.currentY = 0;
        this.lastX = 0;
        this.lastY = 0;
        // 每个波形的高度
        this.itemHeight = 100;
        // 橡皮檫宽度
        this.clearGap = 20;
        this.y_offset = 0;
        // 队列
        this.queue = [];
        this.strokeStyle = "#0f0";
                 
        this.frameSize = 128; // @param frameSize 1秒多少个点
        this.yMax = 1000;
        this.lastY = this.itemHeight / 2;
        this.y_offset = 50;
        this.step = 10; //每次画几个点
        //扫纸速度，默认 25mm/s (1秒25个小格子 每个小格子0.04s)。 0.5表示扫纸速度为 12.5mm/s。2表示扫纸速度为 50mm/s。
        this.speedRatio = 1; 
        this.strokeStyle = '#000000'; //线的样式
        // this.drawInterval = Math.floor((1 / this.frameSize) * 1000 * this.step); // 绘制时间间隔
        this.drawInterval = 6.8

        console.log("itemHeight:",this.itemHeight, this.drawInterval)
    },
    //绘图
    start: function (params) {  // 通过 SelectorQuery 获取 Canvas 节点
      console.log("start")
      if (this.startDraw){
          clearTimeout(timeId)
          lineCtx.clearRect(0, 0, width, height);
          this.startDraw = false
          return
      }
      this.startDraw = true
      // let respWave = new WaveView(128, 1000, 50, 10, 1, '#000000');

      // respWave.loop();
      this.execAddEcgData()
      this.loop()
    },
    execAddEcgData(){
      clearTimeout(this.addTimeId)
      this.addTimeId = this.addData([67,74,-3,30,85,67,85,101,99,121,90,140,87,99,90,86,81,80,77,78,84,80,86,26,74,49,52,59,55,58,69,99,103,125,133,115,137,136,122,110,117,90,80,79,85,124,143,106,119,154,302,386,150,-104,-182,-229,-174,-65,57,85,111,150,154,191,204,194,211,202,202,223,231,239,239,262,250,246,261,266,267,292,317,331,309,327,361,332,334,343,342,340,347,333,354,291,302,318,279,260,282,271,270,269,274,288,278,271,286,261,284,273,272,270,307,270,266,287,303,299,287,294,292,303,318,312,320,306,311,297])
      setTimeout(this.execAddEcgData,1000)
      console.log('add data')
    },
    loop() {
      this.draw();
      // let timeStamp = new Date().getTime()
      // console.log(timeStamp)
      timeId= setTimeout(this.loop, this.drawInterval);
    
      // TODO for test only 添加测试数据，实际中会从后台取
      // this.addData([67,74,-3,30,85,67,85,101,99,121,90,140,87,99,90,86,81,80,77,78,84,80,86,26,74,49,52,59,55,58,69,99,103,125,133,115,137,136,122,110,117,90,80,79,85,124,143,106,119,154,302,386,150,-104,-182,-229,-174,-65,57,85,111,150,154,191,204,194,211,202,202,223,231,239,239,262,250,246,261,266,267,292,317,331,309,327,361,332,334,343,342,340,347,333,354,291,302,318,279,260,282,271,270,269,274,288,278,271,286,261,284,273,272,270,307,270,266,287,303,299,287,294,292,303,318,312,320,306,311,297])
      // console.log("进来了")
    },
    addData(arr) {
      // let timeStamp = new Date().getTime()
      // console.log(timeStamp)
      for (let i = 0; i < arr.length; i++) {
        this.queue.push(arr[i]);
      }
      console.log(this.queue)
    },
    draw() {
      if (this.queue.length <= 128) {
        // console.log("不绘制")
        return
      }
      // console.log('绘制:',this.queue.length)
      // if (this.queue.length == 0) {
      //   return
      // } 
      lineCtx.beginPath();
      lineCtx.strokeStyle = this.strokeStyle;
      if (this.lastX == 0) {
        lineCtx.clearRect(0, 0, this.clearGap, height);
      } else {
        lineCtx.clearRect(this.currentX, 0, this.clearGap, height);
      }
      // lineCtx.fillStyle = "#ffffff";
      // for (let i = 0; i < this.step; i++) {
        
          
          this.currentY = (this.queue.shift()) / this.yMax * this.itemHeight + this.itemHeight;

          // console.log(this.currentY)

      //   if (this.currentY > this.itemHeight) {
      //     this.currentY = this.itemHeight;
      //   }

        lineCtx.moveTo( this.lastX, this.y_offset + this.lastY);
        lineCtx.lineTo( this.currentX, this.y_offset + this.currentY);
        lineCtx.stroke();

        this.lastX = this.currentX;
        this.lastY = this.currentY;

        this.currentX += (grid_width * 25 * this.speedRatio) / this.frameSize;
        if (this.currentX >= width) {
          this.currentX = 0;
          this.lastX = 0;
          console.log('clear')
          
        }
      // }
    },
})

